import * as turf from '@turf/turf'
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import extendDrawBar from '@/js/mapbox-gl/mapbox-gl-draw-bar';
import YTMap from '@/js/map';
import $ from 'jquery'
const drawStatus = {
    'view': ['mapbox-gl-draw_polygon'],
    'selectOne': ['mapbox-gl-draw_uncombine', 'mapbox-gl-draw_trash', 'mapbox-gl-draw_split'],
    'selectMore': ['mapbox-gl-draw_combine', 'mapbox-gl-draw_trash', 'mapbox-gl-draw_dissolve', 'mapbox-gl-draw_split']
}
class MapIndex {

}


var drawUpdateEvent, saveFeatureEvent;
var draw, map, ytMap;
function initMap(para) {
    ytMap = new YTMap({
        map: 'map',
        load: (_map) => {
            map = _map;
            mapLoad(map);
            if (para.load) {
                para.load(map);
            }
        },
        villageClick: para != null ? para.villageClick : null,
        parcelClick: para != null ? para.parcelClick : null
    });
    if (para) {
        drawUpdateEvent = para.drawUpdate;
        saveFeatureEvent = para.saveFeature;
    }
    return ytMap.map;
};
function mapLoad(map) {
    draw = new MapboxDraw({
        displayControlsDefault: false,
        // styles: drawStyle.defaultStyle,
        controls: {
            polygon: true,
            trash: true,
            // combine_features: true,
            // uncombine_features: true
        },
        defaultMode: 'simple_select',
        modes: {
            ...MapboxDraw.modes,
            // splitPolygonMode: SplitPolygonMode,
            // passing_mode_line_string: mapboxGlDrawPassingMode(
            //     MapboxDraw.modes.draw_line_string
            // ),
            // draw_circle: CircleMode,
            // drag_circle: DragCircleMode,
            // direct_select: DirectMode,
            // simple_select: SimpleSelectMode,
            // draw_rectangle: DrawRectangle
        },
        userProperties: true,
    });
    var drawBar = new extendDrawBar({
        draw: draw,
        //dissolve
        buttons: [
            //     {
            //     on: 'click',
            //     action: drawCectangle,
            //     classes: ['mapbox-gl-draw_rectangle'],
            //     title: '创建矩形'
            // },
            // {
            //     on: 'click',
            //     action: drawCircle,
            //     classes: ['mapbox-gl-draw_circle'],
            //     title: '创建圆'
            // },
            {
                isBefore: true,
                on: 'click',
                action: saveFeature,
                classes: ['mapbox-gl-draw_save'],
                title: '保存'
            },
            // {
            //     on: "click",
            //     action: splitPolygon,
            //     classes: ["mapbox-gl-draw_split"],
            //     title: '分割面/多面'
            // },
            // {
            //     on: 'click',
            //     action: drawDissolve,
            //     classes: ['mapbox-gl-draw_dissolve'],
            //     title: '融合'
            // },
            {
                on: "click",
                action: recoverDraw,
                classes: ["mapbox-gl-draw_recover"],
                title: '撤销'
            }
        ],
    });
    map.addControl(drawBar, 'top-left');
    setDrawButtonCN();
    setDrawStatus(drawStatus.view);

    map.on('draw.create', updateArea);
    map.on('draw.delete', updateArea);
    map.on('draw.update', updateArea);
    map.on('draw.delete', () => {
        setDrawStatus(drawStatus.view);
    });
    map.on('draw.selectionchange', () => {
        var seletedCount = draw.getSelectedIds().length;
        if (seletedCount > 1) {
            setDrawStatus(drawStatus.selectMore);
        } else if (seletedCount == 1) {
            setDrawStatus(drawStatus.selectOne);
        } else {
            setDrawStatus(drawStatus.view);
        }
    });
}
var initGeometry;
function recoverDraw() {
    draw.deleteAll();
    if (initGeometry) {
        var bbox = turf.bbox(initGeometry);
        draw.add(initGeometry);
        updateArea();
        map.fitBounds(bbox, {
            padding: { top: 10, bottom: 25, left: 15, right: 5 }
        });
    }
    draw.changeMode('simple_select');
}

function saveFeature() {
    if (saveFeatureEvent) {
        saveFeatureEvent(draw.getAll());
    }
}

function setDrawButtonCN() {
    var cn = {
        'mapbox-gl-draw_polygon': '绘制多边形',
        'mapbox-gl-draw_trash': '删除选中的面/多面',
        'mapbox-gl-draw_combine': '合并选中的多个面（按住Shift多选）',
        'mapbox-gl-draw_uncombine': '取消合并',
    }
    for (const className in cn) {
        if (Object.hasOwnProperty.call(cn, className)) {
            const title = cn[className];
            var buttons = document.getElementsByClassName(className);
            for (let index = 0; index < buttons.length; index++) {
                const button = buttons[index];
                button.title = title;
            }
        }
    }
}
function setDrawStatus(buttons) {
    $('.mapbox-gl-draw_ctrl-draw-btn').attr('disabled', 'disabled');
    if (buttons == undefined) {
        buttons = [];
    }
    buttons.push('mapbox-gl-draw_save', 'mapbox-gl-draw_recover', 'mapbox-gl-draw_polygon',
        'mapbox-gl-draw_circle', 'mapbox-gl-draw_rectangle');
    buttons.forEach(button => {
        $('.' + button).removeAttr('disabled');
    });
}

function updateArea(e) {
    var data = draw.getAll();
    // var answerBox = document.getElementById('calculation-box');
    if (data.features.length > 0) {
        if (drawUpdateEvent) {
            var area = turf.area(data);
            var rounded_area = Math.round(area * 100) / 100;
            drawUpdateEvent(rounded_area);
        }
        // if(drawUpdateEvent){
        //     drawUpdateEvent(rounded_area);
        // }
        // answerBox.innerHTML = '<p>已绘制的图形面积：<strong>' + rounded_area + '</strong> m²</p>';
        // answerBox.style.display = 'block';
    } else {
        if (drawUpdateEvent) {
            drawUpdateEvent(null);
        }
        // answerBox.style.display = 'none';
        // answerBox.innerHTML = '';
    }
}

function addDrawEvent() {

}

function splitPolygon() {
    if (draw.getSelectedIds().length == 0) {
        return;
    }
    try {
        draw.changeMode("splitPolygonMode");
    } catch (err) {
        alert(err.message);
    }
};

function drawCircle() {
    draw.changeMode('draw_circle', { initialRadiusInKm: 0.5 });
}

function drawCectangle() {
    draw.changeMode('draw_rectangle');
}

function drawDissolve() {
    var data = draw.getAll();
    if (data.features.length < 2) {
        //请至少选择两个及以上图形后进行融合操作
        return;
    }
    var newjson = turf.dissolve(data);
    draw.deleteAll();
    draw.add(newjson);
    updateArea();
}

function isArray(arg) {
    if (!Array.isArray) {
        Array.isArray = function (arg) {
            return Object.prototype.toString.call(arg) === '[object Array]';
        };
    }
    return Array.isArray(arg);
}

function drawGeometry(geometry) {
    if (geometry) {
        if (geometry.type == 'MultiPolygon') {
            geometry.coordinates.forEach(coords => {
                //兼容之前错误的数据
                if (isArray(coords) && isArray(coords[0]) && isArray(coords[0][0]) && isArray(coords[0][0][0])) {
                    coords.forEach(coord => {
                        draw.add({
                            type: 'Polygon',
                            coordinates: coord
                        });
                    })
                } else {
                    draw.add({
                        type: 'Polygon',
                        coordinates: coords
                    });
                }
            })
        } else if (geometry.type == 'Polygon') {
            draw.add(geometry);
        }
        var bbox = turf.bbox(geometry);
        draw.changeMode('simple_select');
        updateArea();
        map.fitBounds(bbox, {
            padding: { top: 200, bottom: 200, left: 200, right: 200 }
        });
    }
}

function setInitGeometry(geometry) {
    initGeometry = geometry;
    if (geometry) {
        var bbox = turf.bbox(geometry);
        map.fitBounds(bbox, {
            padding: { top: 200, bottom: 200, left: 200, right: 200 }
        });
    }
}

function addParcelLayer(geometry) {
    $('#ckbparcel').prop('checked', true);
    let layerId = 'parcel';
    if (map.getLayer(layerId)) {
        map.removeLayer(layerId);
    }
    if (map.getSource(layerId)) {
        map.removeSource(layerId);
    }
    if (geometry == null) {
        return;
    }
    map.addSource(layerId, {
        type: 'geojson',
        data: {
            "type": "Feature",
            "properties": {
            },
            "geometry": geometry
        }
    });
    map.addLayer({
        "id": layerId,
        "source": layerId,
        "type": "fill",
        "paint": {
            "fill-color": '#5900ff',
            "fill-opacity": 0.4,
        },
        "layout": {
            "visibility": "visible"
        }
    });
}

function hideParcelLayer() {
    $('#ckbparcel').prop('checked', false);
}

function highlightParcelLayer(highlightIds) {
    ytMap.highlightParcelLayer(map, highlightIds);
}

export default {
    initMap,
    drawGeometry,
    setInitGeometry,
    addParcelLayer,
    hideParcelLayer,
    highlightParcelLayer
}